<?php

namespace App\Recharge;

class Sign
{
    /**
     * 通用
     *
     * @param array $data
     * @param string $key
     * @return string
     */
    public static function currency(array $data, string $key): string
    {
        //签名步骤一：把字典json序列化
        $json = json_encode( $data, 320 );
        //签名步骤二：转化为数组
        $jsonArr = preg_split('/(?<!^)(?!$)/u', $json );
        //签名步骤三：排序
        sort( $jsonArr );
        //签名步骤四：转化为字符串
        $string = implode( '', $jsonArr );
        //签名步骤五：在string后加入secret
        $string = $string . $key;
        //签名步骤六：MD5加密
        return strtolower( md5( $string ) );
    }

    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public static function chengduleige(array $array, string $secret_key): string
    {
        $sign = "";
        ksort($array);
        foreach ($array as $key => $value) {
            if (!$value && ($value != 0)) {
                continue;
            }
            $sign .= $key . "=" . $value . "&";
        }
        $sign .= "AppSecret=" . $secret_key;

        return strtolower(md5($sign));
    }

    /**
     * 分销e获取加密的数据
     *
     * @param array $info
     * @param string $secret_key
     * @return false|string
     */
    public static function fxeOpensslMessage(array $info, string $secret_key): bool|string
    {
        return encryptWithOpenssl( json_encode($info,JSON_UNESCAPED_UNICODE ), $secret_key);
    }

    /**
     * @param array $array
     * @param string $key
     * @return string
     */
    public static function fxeMakeSign(array $array, string $key): string
    {
        ksort($array);
        $signStr = 'app_id='.$array['app_id'].'&channel='.$array['channel'].
            '&format='.$array['format']. '&message='.$array['message']. '&method='.$array['method'].
            '&msgtype='.$array['msgtype']. '&request_id='.$array['request_id']. '&timestamp='.$array['timestamp'].
            '&version='.$array['version'];
        $publicKey = openssl_get_privatekey($key);
        openssl_sign($signStr, $sign, $publicKey);
        // openssl_free_key($publicKey);
        return bin2hex($sign);
    }
}
